import router from './router'
import store from './store'
import { Message } from 'element-ui'
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

const whiteList = ['/login','/home'] // no redirect whitelist

export function findCurrentRoute(routers = [], basePath = '', currentPath = '') {
	var flag = false
	if(basePath === currentPath) {
		flag = true
		return flag
	} else if(routers.length) {
		for(let i in routers) {
			let nextBathPath = basePath == '' ? routers[i].path : (basePath + '/' + routers[i].path)
			if(currentPath === nextBathPath) {
				flag = true
				break;
			} else if(routers[i].children && routers[i].children.length > 0) {
				flag = findCurrentRoute(routers[i].children, nextBathPath, currentPath)
				if(flag) {
					break;
				}
			}
		}
	}
	return flag
}
router.beforeEach(async(to, from, next) => {

	// set page title
	document.title = getPageTitle(to.meta.title)

	// 判断用户是否登录
	const hasToken = getToken()
	if(hasToken) {
		if(to.path === '/login') {
			// 重定向到首页
			await store.dispatch('permission/setPath', '/')
			next({
				path: '/'
			})
		} else {
			//是否存储过登录用户
			const userName = store.getters.userName 
			if(!userName){
				await store.dispatch('user/login')
			}
			//先判断是否有角色
			const hasRoles = store.getters.roles && store.getters.roles.length > 0
			if(!hasRoles){
				await store.dispatch('user/getRoles')
				if(whiteList.indexOf(to.path)>-1){
					next()
				}else{
					//重定向到首页
					await store.dispatch('permission/setPath', '/')
					next({
						path: `/home?redirect=${to.fullPath}`
					})
				}
			}else{
				//查找当前路由是否是有效路由，如果不是跳到首页
				const permission_routes = store.getters.permission_routes
				const { params, query } = to
				const  urlPath  = params.path
				let toPath =urlPath? ('/' + urlPath) : to.path
				let flag = findCurrentRoute(permission_routes, '', toPath)
				if(flag || (whiteList.indexOf(to.path) > -1)) {
					if(to.meta.moduleId) {
						store.dispatch('user/setPageBtns', to.meta)
						console.log('setPageBtns', store.getters.btns)
					}
      				await store.dispatch('permission/setPath',to.path)
					next()
				} else {//重定向到首页
					store.dispatch('permission/setPath', '/')
					next({
						path: '/'
					})
				}
			}
				
		}
	} else {
		// 登录
		await store.dispatch('user/login')
		await store.dispatch('permission/setPath', '/')
		next({
			path: '/'
		})
		/*如果没有后端，前端使用静态路由页面自行调试，请打开这段代码，屏蔽上面的登录请求*/
		/* store.dispatch('permission/generateRoutes',[]).then(() => {
      		console.log('store.getters.permission_routes',store.getters.permission_routes)
		    store.dispatch('permission/setPath',to.path)
        	next()
    	})*/
	}
})

router.afterEach(() => {})